package com.xyz.aspect;

import com.xyz.service.SystemService;
import com.xyz.utils.JwtUtils;
import org.apache.commons.lang3.BooleanUtils;
import org.apache.commons.lang3.StringUtils;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Objects;

/**
 * @author 夏永泽
 * @date 2022/3/29
 */
@Component
@Aspect
public class RoleAspect {
    private final SystemService service;

    public RoleAspect(SystemService service) {
        this.service = service;
    }

    @Pointcut("@annotation(com.xyz.annotation.AdminRole)")
    void admin(){}

    @Before("admin()")
    public void adminRole(JoinPoint joinPoint) throws IllegalAccessException {
        //获取request
        final ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        if (Objects.isNull(requestAttributes)) {
            throw new RuntimeException();
        }
        HttpServletRequest request = requestAttributes.getRequest();
        String token = request.getHeader("token");
        if (StringUtils.isEmpty(token) || BooleanUtils.isFalse(JwtUtils.verify(token))) {
            throw new IllegalAccessException();
        }
        Integer role = (Integer) JwtUtils.parseToken(token).get("role");
        if (BooleanUtils.isFalse(role == 1)) {
            throw new IllegalAccessException();
        }
    }
}
